package com.focus.pay.core.utils;

import cn.hutool.http.*;
import cn.hutool.json.JSONUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import javax.net.ssl.SSLSocketFactory;
import java.util.Map;


/**
 * @ClassName HttpUtils
 * @Description : http工具
 * @Return :
 * @Author : 赵参谋
 * @Date : 2020/9/26 10:58
*/
public class HttpClientUtils {

    private static final Log log = LogFactory.get();

    private static ContentType contentType = ContentType.JSON;

    public static <T> String doPost(String url,T t){
        return execStr(Method.POST,url, JSONUtil.toJsonStr(t),null,null,contentType);
    }

    public static String doPost(String url,String body){
        return execStr(Method.POST,url,body,null,null,contentType);
    }

    public static String doPost(String url,String body,Map head){
        return execStr(Method.POST,url,body,head,null,contentType);
    }

    public static String doPost(String url, String body, SSLSocketFactory sslFactory){
        return execStr(Method.POST,url,body,null,sslFactory,contentType);
    }

    public static String doGet(String url){
        return execStr(Method.GET,url,null,null,null,null);
    }

    public static String doGet(String url,Map head){
        return execStr(Method.GET,url,null,head,null,null);
    }

    public static byte[] download(String url){
        return execByte(Method.GET,url,null,null,null,null);
    }

    public static byte[] download(String url,Map head){
        return execByte(Method.GET,url,null,head,null,null);
    }

    private static String execStr(Method method,String url, String body, Map head,SSLSocketFactory sslFactory,ContentType contentType){
        log.info("执行HTTP请求:METHOD:{},URL:{},BODY:{}",method.toString(),url,body);
        String result = new HttpRequest(url).method(method).header(head).contentType(contentType.getValue()).setSSLSocketFactory(sslFactory).body(body).execute().body();
        log.info("RESULT:{}",result);
        return  result;
    }

    private static byte[] execByte(Method method,String url, String body, Map head,SSLSocketFactory sslFactory,ContentType contentType){
        log.info("执行HTTP请求:METHOD:{},URL:{},BODY:{}",method.toString(),url,body);
        return new HttpRequest(url).method(method).header(head).contentType(contentType.getValue()).setSSLSocketFactory(sslFactory).body(body).execute().bodyBytes();
    }

}
